<template>
  <div>
    <div style="display: flex; height: 100%">
      <base-layout title="组织机构" ref="organLayout" style="width: 20%" :bottonShow="false" :isPage="false"
                   :operateButtonSwitch="false" :mainColor="mainColor"
      >
        <div slot="main" style="height: 100%">
          <base-tree ref="baseTree" :isCenter="false" :isSaveBtn="false" :Allshow="false" :showCheckbox="false"
                     :menuData="orangData" @handleNodeClick="orangClick"
          ></base-tree>
        </div>
      </base-layout>
      <base-layout title="用户信息" ref="userLayout" @pageChange="pageChange" style="width: 80%"
                   :buttonList="buttonList" :defaultButtonSwitch="false" @onFuncBtn="getFuncBtn" :isPage="true"
      >
        <div slot="main" slot-scope="{ tableHeight }" style="height: 100%">
          <base-table ref="userCustomtable" :border="true" :showIndex="false" :tabLoading.sync="tabLoading"
                      @radioChange="userRadioChange" :slotrow="true" :tableHeight="tableHeight" :tableData="tableData"
                      :tableColumn="tableColumn"
          >
          </base-table>
        </div>
      </base-layout>
    </div>
    <right-dialog ref="rightDialog" :menuData="menuData" v-if="permissionPopup"></right-dialog>

    <base-dialog :closeEscape="true" :showClose="true" :closeModal="false" :dialogVisible.sync="settingDialog"
                 class="userDialog" title="权限设置" width="50vw" top="5vh" :footerShow="true"
                 @handleConfirmClick="settingConfirmClick"
    >
      <base-layout :showTitle="false" :defaultButtonSwitch="false">
        <div slot="main">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick" :before-leave="beforeLeave">
            <el-tab-pane label="菜单权限" name="jurisdictionSetting">
              <jurisdiction-Setting ref="jurisdictionSetting" :menuData="menuData"></jurisdiction-Setting>
            </el-tab-pane>
            <el-tab-pane label="按钮权限" name="buttonSetting">
              <button-setting ref="buttonSetting"></button-setting>
            </el-tab-pane>
            <el-tab-pane label="数据权限" name="dataSetting">
              <data-setting ref="dataSetting"></data-setting>
            </el-tab-pane>
          </el-tabs>
        </div>
      </base-layout>
    </base-dialog>
  </div>
</template>

<script>
import router from '@/router'
import baseLayout from '@/components/base/baseLayout'
import baseTable from '@/components/base/baseTable'
import baseDialog from '@/components/base/BaseNewDialog/index.vue'
import baseForm from '@/components/base/baseNewForm/index.vue'
import baseTree from '@/components/base/BaseMenuTree/index.vue'
import rightDialog from './rightDialog'
import jurisdictionSetting from './jurisdictionSetting.vue'
import buttonSetting from './buttonSetting.vue'
import dataSetting from './dataSetting.vue'
import configData from './configData'
import { getCompanyId } from '@/utils/auth'
import { GetMenuTree } from '@/api/apis/menuManage'
import { userGetBillList } from '@/api/apis/userInformation'
import { GetOrganTree } from '@/api/apis/organization'
import {
  GetPppedomSet,
  GetMenuButton,
  GetAllButton,
  GetAllBillDataPepedom,
  GetAllBilldata,
  PopedomSaveData
} from '@/api/apis/jurisdiction'
import { authApi } from '@/api/apis/auth'

export default {
  name: 'review',
  components: {
    buttonSetting,
    dataSetting,
    baseLayout,
    baseTable,
    baseDialog,
    baseForm,
    baseTree,
    jurisdictionSetting,
    rightDialog
  },
  data() {
    return {
      activeName: 'jurisdictionSetting',
      radioIndex: false,
      userRadioId: false,
      settingDialog: false,
      // tableHeight: 'calc(100vh - 227px)',
      mainColor: '#f8f8f8',
      tabLoading: false,
      tableData: [],
      // 搜索配置
      menuData: [],
      orangData: [],
      buttonList: [
        {
          icon: 'el-icon-plus',
          menuName: '权限设置',
          btnFunciton: 'setting'
        }
      ],
      pageModel: {
        pageNum: 1,
        pageSize: 20,
        organId: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      buttonArray: [],
      allButtonList: [],
      menuIDs: [],
      menuList: [],
      menuPopedom: [],
      permissionPopup: false
    }
  },
  computed: {
    // 表头配置
    tableColumn() {
      return configData.tableColumnJson
    }
  },
  watch: {
    settingDialog: {
      deep: true,
      handler(newValue, oldValue) {
        if (newValue == false) {
          this.$refs.dataSetting.dataList = []
          this.$refs.jurisdictionSetting.$refs.menuTree.$refs.elTree.setCheckedKeys(
            []
          )
          this.$refs.buttonSetting.classifyButtonList = []
        }
      }
    }
  },
  created() {
  },
  onShow() {
  },
  mounted() {
    this.initPage()
    this.getMenuData()
  },
  filters: {},
  methods: {
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName == 'jurisdictionSetting') {
        this.menuPopedom = this.$refs.jurisdictionSetting.menuPopedom
        this.checkdata = this.$refs.jurisdictionSetting.checkdata
      }
      if (
        oldActiveName == 'jurisdictionSetting' &&
        activeName == 'buttonSetting'
      ) {
        if (this.menuPopedom.length == 0) {
          this.$vmNews('当前用户未分配菜单权限')
          return false
        }
      }
      if (oldActiveName == 'dataSetting' && activeName == 'buttonSetting') {
        // return false
      }
    },
    // 切换tab
    handleClick(tab, event) {
      if (this.activeName == 'buttonSetting') {
        this.checkdata = this.$refs.jurisdictionSetting.checkdata
        this.$refs.buttonSetting.GetAllButtonList(
          this.menuPopedom,
          this.checkdata
        )
      }
      if (this.activeName == 'dataSetting') {
        this.$refs.dataSetting.inPage()
      }
    },
    // 获取菜单选中
    getMenuIDs(menuData) {
      menuData.forEach((el) => {
        if (el.type) {
          this.menuList.push(el)
          this.menuIDs.push(el.id)
        }
        if (el.children != null && el.children && el.children.length) {
          this.getMenuIDs(el.children)
        }
      })
    },
    // 初始化页面
    initPage() {
      this.getTableList()
      this.getOrganList()
    },
    //获取菜单树
    async getMenuData() {
      // let res = await GetMenuButton({});
      let res = await authApi('sysMenuConfigService', '', 'queryEntityTree', '', { state: 0 })
      if (res.status == 200) {
        let arr = res.attribute
        this.menuData = res.attribute
        this.changeMenu(this.menuData, 0)
        // this.getButtonArray(this.menuData)
      }
    },
    // 菜单树添加参数
    changeMenu(data, num) {
      let level = num
      level = level + 1
      data.forEach((el) => {
        el.buttonList = []
        el.type = false
        if (el.children != null && el.children && el.children.length) {
          this.changeMenu(el.children, level)
        }
      })
    },
    addToButtonList(arr, newArr) {
      newArr.forEach((newItem) => {
        this.addToButtonListRecursive(
          arr,
          newItem.op_MenuID,
          newItem.op_OperateKindList
        )
      })
      return arr
    },
    addToButtonListRecursive(arr, targetId, operateKindList) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        if (item.id == targetId) {
          item.buttonList = operateKindList.split(',')
          return item
        }
        if (item.children && item.children.length > 0) {
          this.addToButtonListRecursive(
            item.children,
            targetId,
            operateKindList
          )
        }
      }
    },
    // 获取用户信息列表
    async getTableList() {
      this.tabLoading = true
      this.tableData = []
      let params = {
        ...this.pageModel
      }
      let res = await authApi('sysUserService', '', 'queryEntityPage', '', params)
      if (res.status == 200) {
        this.tableData = res.attribute.list
        this.$nextTick(() => {
          this.$refs.userCustomtable.clearRadioIndex()
          this.$refs.userLayout.setPageTotal(res.attribute.total)
        })
        this.tabLoading = false
      }
    },
    getButtonArray(menuData) {
      menuData.forEach((el, index) => {
        this.allButtonList.forEach((item) => {
          if (el.id == item.MenuID) {
            item.active = false
            el.buttonList.push(item)
          }
        })
        if (el.children != null && el.children && el.children.length) {
          this.getButtonArray(el.children)
        }
      })
    },
    // 单选
    userRadioChange(val) {
      this.radioIndex = val.index
      this.userRadioId = val.id
    },
    // 获取组织列表
    async getOrganList() {
      this.$refs.baseTree.treeLoading = true
      setTimeout(() => {
        this.$refs.baseTree.treeLoading = false
      }, 3000)
      const res = await authApi('sysOrganService', '', 'queryEntityTree', '', { state: 0 })
      // let res = await GetOrganTree(params);
      if (res.status == 200) {
        this.orangData = res.attribute
        this.$refs.baseTree.treeLoading = false
      }
    },
    // 树状图点击
    orangClick(data) {
      this.pageModel.organId = data.id
      this.resetTable()
      // this.result()
    },
    resetTable() {
      this.pageModel.pageNum = 1
      this.userRadioId = false
      this.radioIndex = false
      this.$nextTick(() => {
        this.$refs.userCustomtable.clearRadioIndex()
        this.$refs.userLayout.pageClear()
      })
      this.getTableList()
    },
    // 操作按钮事件
    getFuncBtn(btnEven) {
      if (this.radioIndex === false) {
        this.$vmNews('请选择一条数据')
        return
      }
      this[btnEven.btnFunciton]()
    },
    //点击权限设置
    async setting() {
      this.getMenuData()
      this.permissionPopup = true
      this.$nextTick(async() => {
        this.$refs.rightDialog.drawer = true
        this.$refs.rightDialog.buttonLoading = true
        let params = {
          id: this.userRadioId,
          kindId: 1
        }
        const res = await authApi('sysUserService', '', 'jurisdiction', '',params)
        if (res.status == 200) {
          const data = res.attribute
          this.$refs.rightDialog.exhibitList(res.attribute.menvVoList,res.attribute.homeList,this.userRadioId)
        }
      })
    },
    // setting() {
    // 	this.settingDialog = true
    // 	this.activeName = "jurisdictionSetting"
    // 	this.GetPppedomData()
    // },
    async GetPppedomData() {
      let params = {
        objectID: this.userRadioId,
        kindid: 1
      }

      let res = await GetPppedomSet(params)
      this.$refs.jurisdictionSetting.menuLoading = true
      setTimeout(() => {
        this.$refs.jurisdictionSetting.menuLoading = false
      }, 3000)
      if (res.code == 1) {
        const data = res.data
        let menuIDs =
          data[0].length > 0 ? data[0][0].fp_MenuIdList.split(',') : []
        this.$refs.jurisdictionSetting.$refs.menuTree.selectData = menuIDs
        this.$refs.jurisdictionSetting.$refs.menuTree.checkChange(menuIDs)
        let buttonPopedom = this.getbuttonPopedomList(res.data[1])
        this.$refs.buttonSetting.buttonPopedom = buttonPopedom
        let activeList = this.getActiveList(res.data[2])
        this.$refs.dataSetting.activeList = activeList
        this.$refs.jurisdictionSetting.menuLoading = false
        // selectData
      }
    },
    getActiveList(data) {
      let array = []
      data.forEach((el) => {
        el.dp_popeList.split(',').forEach((item) => {
          array.push(item)
        })
      })
      return array
    },
    getbuttonPopedomList(data) {
      let array = []
      data.forEach((el) => {
        el.op_OperateKindList.split(',').forEach((item) => {
          array.push(item)
        })
      })
      return array
    },
    pageChange(model) {
      this.pageModel.pageNum = model.page
      this.pageModel.pageSize = model.limit
      this.getTableList()
    },
    settingConfirmClick() {
      let menuPopedom = this.$refs.jurisdictionSetting.menuPopedom.join(',')
      let buttonPopedom = this.getButtonPopedom(
        this.$refs.buttonSetting.classifyButtonList
      )
      let dataPopedom = this.getDataPopedom(this.$refs.dataSetting.dataList)
      let params = {
        kindid: 1,
        objectID: this.userRadioId,
        menuPopedom: menuPopedom,
        buttonPopedom: buttonPopedom,
        dataPopedom: dataPopedom
      }
      this.saveData(params)
    },
    async saveData(params) {
      let res = await PopedomSaveData(params)
      if (res.code == 1) {
        this.$vmNews('保存成功', 'success')
        this.activeName = 'jurisdictionSetting'
        this.settingDialog = false
        this.$store.dispatch('GenerateRoutes').then((accessRoutes) => {
          // 根据roles权限生成可访问的路由表
          for (let i = 0, length = accessRoutes.length; i < length; i += 1) {
            const element = accessRoutes[i]
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
          }
          localStorage.setItem('routeList', JSON.stringify(accessRoutes))
        })
      }
    },
    getDataPopedom(dataPopedom) {
      let array = []
      dataPopedom.forEach((el) => {
        el.dp_popeList = []
        el.buttonList.forEach((item) => {
          if (item.type) {
            el.dp_popeList.push(item.id)
          }
        })
      })
      dataPopedom.forEach((el) => {
        if (el.dp_popeList.length > 0) {
          let params = {
            dp_billKindID: el.billKindID,
            dp_popeList: el.dp_popeList.join(',')
          }
          array.push(params)
        }
      })
      return array
    },
    getButtonPopedom(buttonPopedom) {
      let array = []
      // let op_OperateKindList = []
      buttonPopedom.forEach((el) => {
        el.op_MenuID = el.id
        el.op_OperateKindList = []
        el.buttonList.forEach((item) => {
          if (item.type) {
            el.op_OperateKindList.push(item.id)
          }
        })
      })
      buttonPopedom.forEach((el) => {
        if (el.op_OperateKindList.length > 0) {
          let params = {
            op_MenuID: el.op_MenuID,
            op_OperateKindList: el.op_OperateKindList.join(',')
          }
          array.push(params)
        }
      })
      return array
    }
  }
}
</script>
<style scoped lang="scss">
> > > .el-dialog__body {
  padding: 0 25px;
}
</style>
<style scoped lang="scss">
.roleName {
  padding: 10px 0;
  width: 90px;
  border: 2px solid #f2f2f2;
  background-color: #f2f2f2;
  margin: 0px 10px 10px 0px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 0 0 2px #f2f2f2;
  border-radius: 5px;
}

.active {
  background-color: #00a490;
  border: 2px solid #ffffff;
  color: white;
  box-shadow: 0 0 0 2px #00a490;
}

.bigTitle {
  padding-bottom: 10px;
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ccc;
}

.organizationBody {
  display: flex;
  justify-content: space-evenly;
  background-color: #f2f3f4;
  padding: 10px;
}
</style>
